<template>
  <div class="page-content">
    <div class="header">
      <h3>流量统计</h3>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="服务器流量统计" name="server">
        <div class="filter-bar">
          <el-form :inline="true" :model="serverForm">
            <el-form-item label="选择服务器">
              <el-select v-model="serverForm.consul_id" placeholder="请选择服务器" style="width: 200px">
                <el-option
                  v-for="node in nodeList"
                  :key="node.service_id"
                  :label="node.service_name"
                  :value="node.service_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围">
              <div class="date-range-container">
                <el-date-picker
                  v-model="serverForm.dateRange[0]"
                  type="datetime"
                  placeholder="开始日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 00:00:00')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
                <span class="date-separator">至</span>
                <el-date-picker
                  v-model="serverForm.dateRange[1]"
                  type="datetime"
                  placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 23:59:59')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleServerQuery">查询</el-button>
              <el-button @click="resetServerForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="stat-cards" v-loading="serverLoading">
          <el-row :gutter="24">
            <el-col :span="6" v-for="(item, index) in [
              { title: '总流量', value: formatTraffic(serverStats.total_traffic || 0), icon: DataLine, color: 'blue' },
              { title: '平均流量', value: formatTrafficRate(serverStats.average_traffic || 0), icon: TrendCharts, color: 'green' },
              { title: '总时长', value: formatTime(serverStats.total_time || 0), icon: Timer, color: 'orange' },
              { title: '记录数', value: serverStats.count || 0, icon: Document, color: 'purple' }
            ]" :key="index">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-card-content">
                  <div class="stat-icon" :class="item.color">
                    <el-icon><component :is="item.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-title">{{ item.title }}</div>
                    <div class="stat-value">{{ item.value }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <el-tab-pane label="设备流量统计" name="device">
        <div class="filter-bar">
          <el-form :inline="true" :model="deviceForm">
            <el-form-item label="选择设备">
              <el-input
                v-model.number="deviceForm.phone_id"
                placeholder="请输入设备ID"
                style="width: 200px"
                clearable
                type="number"
              />
            </el-form-item>
            <el-form-item label="时间范围">
              <div class="date-range-container">
                <el-date-picker
                  v-model="deviceForm.dateRange[0]"
                  type="datetime"
                  placeholder="开始日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 00:00:00')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
                <span class="date-separator">至</span>
                <el-date-picker
                  v-model="deviceForm.dateRange[1]"
                  type="datetime"
                  placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 23:59:59')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleDeviceQuery">查询</el-button>
              <el-button @click="resetDeviceForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="stat-cards" v-loading="deviceLoading">
          <el-row :gutter="24">
            <el-col :span="6" v-for="(item, index) in [
              { title: '总流量', value: formatTraffic(deviceStats.total_traffic || 0), icon: DataLine, color: 'blue' },
              { title: '平均流量', value: formatTrafficRate(deviceStats.average_traffic || 0), icon: TrendCharts, color: 'green' },
              { title: '总时长', value: formatTime(deviceStats.total_time || 0), icon: Timer, color: 'orange' },
              { title: '记录数', value: deviceStats.count || 0, icon: Document, color: 'purple' }
            ]" :key="index">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-card-content">
                  <div class="stat-icon" :class="item.color">
                    <el-icon><component :is="item.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-title">{{ item.title }}</div>
                    <div class="stat-value">{{ item.value }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <el-tab-pane label="用户流量统计" name="user">
        <div class="filter-bar">
          <el-form :inline="true" :model="userForm">
            <el-form-item label="选择用户">
              <el-input
                v-model.number="userForm.user_id"
                placeholder="请输入用户ID"
                style="width: 200px"
                clearable
                type="number"
              />
            </el-form-item>
            <el-form-item label="时间范围">
              <div class="date-range-container">
                <el-date-picker
                  v-model="userForm.dateRange[0]"
                  type="datetime"
                  placeholder="开始日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 00:00:00')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
                <span class="date-separator">至</span>
                <el-date-picker
                  v-model="userForm.dateRange[1]"
                  type="datetime"
                  placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date('2000-01-01 23:59:59')"
                  style="width: 180px"
                  :editable="false"
                  :clearable="true"
                  teleported
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUserQuery">查询</el-button>
              <el-button @click="resetUserForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="stat-cards" v-loading="userLoading">
          <el-row :gutter="24">
            <el-col :span="6" v-for="(item, index) in [
              { title: '总流量', value: formatTraffic(userStats.total_traffic || 0), icon: DataLine, color: 'blue' },
              { title: '平均流量', value: formatTrafficRate(userStats.average_traffic || 0), icon: TrendCharts, color: 'green' },
              { title: '总时长', value: formatTime(userStats.total_time || 0), icon: Timer, color: 'orange' },
              { title: '记录数', value: userStats.count || 0, icon: Document, color: 'purple' }
            ]" :key="index">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-card-content">
                  <div class="stat-icon" :class="item.color">
                    <el-icon><component :is="item.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-title">{{ item.title }}</div>
                    <div class="stat-value">{{ item.value }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DataLine, TrendCharts, Timer, Document } from '@element-plus/icons-vue'
import { 
  getServerTrafficStats, 
  getDeviceTrafficStats, 
  getUserTrafficStats,
  type TrafficStatParams
} from '@/Newapi/traffic'
import { getNodeList } from '@/Newapi/device'

// 格式化日期为字符串
const formatDateToString = (date: Date, withTime = true): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  if (withTime) {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return `${year}-${month}-${day}`
}

// 获取今天开始时间
const getTodayStart = (): string => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return formatDateToString(today)
}

// 获取今天结束时间
const getTodayEnd = (): string => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  return formatDateToString(today)
}

// 当前活动标签
const activeTab = ref('server')

// 节点列表
interface NodeInfo {
  service_id: string
  service_name: string
}

const nodeList = ref<NodeInfo[]>([])
// 设备列表
const deviceList = ref<any[]>([])
// 用户列表
const userList = ref<any[]>([])

// 服务器表单
const serverForm = reactive({
  consul_id: '',
  dateRange: [
    getTodayStart(),
    getTodayEnd()
  ]
})

// 设备表单
const deviceForm = reactive({
  phone_id: undefined as number | undefined,
  dateRange: [
    getTodayStart(),
    getTodayEnd()
  ]
})

// 用户表单
const userForm = reactive({
  user_id: undefined as number | undefined,
  dateRange: [
    getTodayStart(),
    getTodayEnd()
  ]
})

// 加载状态
const serverLoading = ref(false)
const deviceLoading = ref(false)
const userLoading = ref(false)

// 统计数据
interface StatData {
  total_traffic: number
  average_traffic: number
  total_time: number
  count: number
}

const serverStats = ref<StatData>({
  total_traffic: 0,
  average_traffic: 0,
  total_time: 0,
  count: 0
})
const deviceStats = ref<StatData>({
  total_traffic: 0,
  average_traffic: 0,
  total_time: 0,
  count: 0
})
const userStats = ref<StatData>({
  total_traffic: 0,
  average_traffic: 0,
  total_time: 0,
  count: 0
})

// 格式化流量显示
const formatTraffic = (bytes: number) => {
  if (bytes === 0) return '0 KB'
  
  // 输入值已经是KB，需要从KB开始转换
  const units = ['KB', 'MB', 'GB', 'TB', 'PB']
  const k = 1024
  let value = bytes
  let i = 0
  
  while (value >= k && i < units.length - 1) {
    value /= k
    i++
  }
  
  return parseFloat(value.toFixed(2)) + ' ' + units[i]
}

// 格式化流量速率
const formatTrafficRate = (bytesPerSecond: number) => {
  if (bytesPerSecond === 0) return '0 KB/s'
  
  // 输入值已经是KB/s，从KB/s开始转换
  const units = ['KB/s', 'MB/s', 'GB/s', 'TB/s']
  const k = 1024
  let value = bytesPerSecond
  let i = 0
  
  while (value >= k && i < units.length - 1) {
    value /= k
    i++
  }
  
  return parseFloat(value.toFixed(2)) + ' ' + units[i]
}

// 格式化时间
const formatTime = (seconds: number) => {
  if (seconds < 60) {
    return seconds + '秒'
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    return minutes + '分钟' + (seconds % 60 ? (seconds % 60) + '秒' : '')
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return hours + '小时' + (minutes ? minutes + '分钟' : '')
  }
}

// 获取节点列表
const fetchNodeList = async () => {
  try {
    const result = await getNodeList()
    if (result.code === 200) {
      nodeList.value = Object.values(result.data || {}).map((node: any) => ({
        service_id: node.service_id,
        service_name: node.service_name
      }))
      
      if (nodeList.value.length > 0) {
        serverForm.consul_id = nodeList.value[0].service_id
      }
    } else {
      ElMessage.error(result.msg || '获取节点列表失败')
    }
  } catch (error) {
    console.error('获取节点列表失败:', error)
    ElMessage.error('获取节点列表失败')
  }
}

// 查询服务器流量
const handleServerQuery = async () => {
  if (!serverForm.consul_id) {
    ElMessage.warning('请选择服务器')
    return
  }
  
  serverLoading.value = true
  try {
    const params = {
      consul_id: serverForm.consul_id,
      start_time: serverForm.dateRange[0],
      end_time: serverForm.dateRange[1]
    }
    
    const result = await getServerTrafficStats(params)
    if (result.code === 200) {
      const responseData = result.data || {}
      serverStats.value = {
        total_traffic: Number(responseData.total_traffic || 0),
        average_traffic: Number(responseData.average_traffic || 0),
        total_time: Number(responseData.total_time || 0),
        count: Number(responseData.count || 0)
      }
    } else {
      ElMessage.error(result.msg || '获取服务器流量统计失败')
    }
  } catch (error) {
    console.error('获取服务器流量统计失败:', error)
    ElMessage.error('获取服务器流量统计失败')
  } finally {
    serverLoading.value = false
  }
}

// 查询设备流量
const handleDeviceQuery = async () => {
  if (!deviceForm.phone_id) {
    ElMessage.warning('请输入设备ID')
    return
  }
  
  deviceLoading.value = true
  try {
    const params = {
      phone_id: deviceForm.phone_id,
      start_time: deviceForm.dateRange[0],
      end_time: deviceForm.dateRange[1]
    }
    
    const result = await getDeviceTrafficStats(params)
    if (result.code === 200) {
      const responseData = result.data || {}
      deviceStats.value = {
        total_traffic: Number(responseData.total_traffic || 0),
        average_traffic: Number(responseData.average_traffic || 0),
        total_time: Number(responseData.total_time || 0),
        count: Number(responseData.count || 0)
      }
    } else {
      ElMessage.error(result.msg || '获取设备流量统计失败')
    }
  } catch (error) {
    console.error('获取设备流量统计失败:', error)
    ElMessage.error('获取设备流量统计失败')
  } finally {
    deviceLoading.value = false
  }
}

// 查询用户流量
const handleUserQuery = async () => {
  if (!userForm.user_id) {
    ElMessage.warning('请输入用户ID')
    return
  }
  
  userLoading.value = true
  try {
    const params = {
      user_id: userForm.user_id,
      start_time: userForm.dateRange[0],
      end_time: userForm.dateRange[1]
    }
    
    const result = await getUserTrafficStats(params)
    if (result.code === 200) {
      const responseData = result.data || {}
      userStats.value = {
        total_traffic: Number(responseData.total_traffic || 0),
        average_traffic: Number(responseData.average_traffic || 0),
        total_time: Number(responseData.total_time || 0),
        count: Number(responseData.count || 0)
      }
    } else {
      ElMessage.error(result.msg || '获取用户流量统计失败')
    }
  } catch (error) {
    console.error('获取用户流量统计失败:', error)
    ElMessage.error('获取用户流量统计失败')
  } finally {
    userLoading.value = false
  }
}

// 重置服务器表单
const resetServerForm = () => {
  serverForm.consul_id = nodeList.value.length > 0 ? nodeList.value[0].service_id : ''
  serverForm.dateRange = [
    getTodayStart(),
    getTodayEnd()
  ]
  serverStats.value = {
    total_traffic: 0,
    average_traffic: 0,
    total_time: 0,
    count: 0
  }
}

// 重置设备表单
const resetDeviceForm = () => {
  deviceForm.phone_id = undefined
  deviceForm.dateRange = [
    getTodayStart(),
    getTodayEnd()
  ]
  deviceStats.value = {
    total_traffic: 0,
    average_traffic: 0,
    total_time: 0,
    count: 0
  }
}

// 重置用户表单
const resetUserForm = () => {
  userForm.user_id = undefined
  userForm.dateRange = [
    getTodayStart(),
    getTodayEnd()
  ]
  userStats.value = {
    total_traffic: 0,
    average_traffic: 0,
    total_time: 0,
    count: 0
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchNodeList()
  // 默认查询服务器数据
  if (serverForm.consul_id) {
    handleServerQuery()
  }
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  /* 禁用触摸事件 */
  :deep(.el-date-editor) {
    touch-action: none;
  }

  /* 解决日期选择器弹出层问题 */
  :deep(.el-picker-panel) {
    touch-action: pan-y;
  }
  
  :deep(.el-picker__popper) {
    touch-action: none;
  }

  .date-range-container {
    display: flex;
    align-items: center;
    
    .date-separator {
      margin: 0 5px;
    }
  }

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);
    margin-bottom: 20px;

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .filter-bar {
    margin-bottom: 20px;
  }
  
  .stat-cards {
    margin-top: 20px;
    
    .stat-card {
      border-radius: 8px;
      overflow: hidden;
      transition: all 0.3s;
      height: 100%;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
      }
      
      .stat-card-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
        padding: 20px;
      }
      
      .stat-icon {
        width: 64px;
        height: 64px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16px;
        
        .el-icon {
          font-size: 32px;
          color: white;
        }
        
        &.blue {
          background: linear-gradient(135deg, #1890ff, #096dd9);
        }
        
        &.green {
          background: linear-gradient(135deg, #52c41a, #389e0d);
        }
        
        &.orange {
          background: linear-gradient(135deg, #fa8c16, #d46b08);
        }
        
        &.purple {
          background: linear-gradient(135deg, #722ed1, #531dab);
        }
      }
      
      .stat-info {
        width: 100%;
        
        .stat-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 8px;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}
</style> 